import { getTokenKey } from "../../utils/auth";
import { getLocationInfo} from "../../utils/location";
import { handleFileUploading, deleteFile } from "../../utils/file.js";
import { deleteMarker, deleteFileFromDbs,uploadInitFile } from "../../utils/user";

const app = getApp();
Page({
  data: {
    markerId: 0,
    current_loc_latitude:'',
    current_loc_longitude:'',
    current_loc_title:'',
    equipment_status:['正常','故障'],
    choose_status:'',
    is_choose_status:false,
    flowRate: '',
    flowRate_diabled:false,
    description:'',
    isUpdate:false,
    imgList:[],
    hydrantId: 0
  },

  onLoad(options){
    if(options.id){
      this.updateInit(options)
    }else{
      getLocationInfo().then(res=>{
        this.setData({
          current_loc_latitude:res.latitude,
          current_loc_longitude:res.longitude,
          current_loc_title: res.title
        })
      }) 
    } 
  },


  updateInit(options){
    console.log(options)
    this.setData({
      isUpdate: true,
      current_loc_latitude: options.latitude,
      current_loc_longitude: options.longitude,
      description: options.description,
      markerId: options.id,
      current_loc_title: options.title,
      imgList: options.imageList===undefined ? [] : JSON.parse(decodeURIComponent(options.imageList))
    })
  },

  chooseImage(e){
    this.setData({
      imgList: e.detail
    })
  },
 
  radioChange(e){
    const{value} = e.detail
    const flowRate = this.selectComponent('.flowInput')
    var that = this
    if(value === '故障'){
      that.setData({
        flowRate:0,
        flowRate_diabled:true,
        choose_status:value,
        is_choose_status:true
      })
      flowRate.setData({
        isError:false
      })
    }else{
      that.setData({
        choose_status:value,
        is_choose_status:true,
        flowRate:'',
        flowRate_diabled:false,
      })
    }  
  },

  onTextareaConfirm(e){
    console.log('e',e)
    const{value} = e.detail
    this.setData({
      description:value
    })
  },

  // 提交表格是否有错误
  _isFormReady(){
    let isReady = true;
    if(!this.data.is_choose_status){
      isReady = false
    }
    const children = this.selectAllComponents('.detail-input')
    children.forEach(item=>{
      const isError =item.data.isError
      const value = item.data.value
      if(isError==true || value===''){
        isReady = false
      }
    })
   return isReady
  },

  async submitForm(){
    if(this._isFormReady()){
      var that = this
      this.searchHydrant().then(res => {
      if(res.code == 401){
        wx.showModal({
          title: '未登陆',
          content: '请在我的页面进行登陆',
          success (res) { 
            if (res.confirm) {
              wx.switchTab({
                url: '../homePage/index',
              })
            } 
          }
        })
        return
      }
      if(res.code != 401 && res.totalElements != 0) {
        console.log(res.totalElements)
        wx.showModal({
          title: '提示',
          content:'附近存在消火栓，请核对',
          showCancel:false,
          success (res) { 
            if (res.confirm) {
              wx.switchTab({
                url: '../index/index',
              })
            } 
          }
        });
      }else{
        wx.showLoading({
          title: '正在提交',
        })
        
        // 添加基础信息
        this.addBasicInfo().then(resp=>{
          console.log('debug',resp)
          if(resp.id){
            that.setData({
              hydrantId: resp.id
            })
            if(that.data.imgList.length!==0){
              that.uploadFiles();
            }
            wx.hideLoading();
            wx.showModal({
              title: '提交成功',
              success () { 
                wx.switchTab({
                  url: '../index/index',
                })
              }
            })   
          }else {
            wx.showModal({
              title: '基础信息上传出错'
            })
          }
        })
      }
      })
    }else{
      wx.showModal({
        title: '提交失败',
        content:'信息有误或必要信息未填写！请修正'
      })
    }
  },

  searchHydrant(){
    return new Promise((resolve)=>{
      resolve(
        app.call({
        path:'/hydrant/search',
        method: 'post',
        header: {
          'X-WX-SERVICE': 'fire-assistant-s',
          'tokens': getTokenKey()//必须添加#######
        },
        data : {
          minLatitude : parseFloat(this.data.current_loc_latitude) - 0.00001,
          maxLatitude : parseFloat(this.data.current_loc_latitude) + 0.00001,
          minLongitude: parseFloat(this.data.current_loc_longitude) - 0.00001,
          maxLongitude: parseFloat(this.data.current_loc_longitude) + 0.00001
        }
      }))
    })
  },
  addBasicInfo(){
    return new Promise((resolve) => {
      resolve(
        app.call({
          path:'/hydrant/weChat/add',
          method: 'post',
          header: {
            'X-WX-SERVICE': 'fire-assistant-s',
            'tokens': getTokenKey()//必须添加#######
          },
          data: {
            name:"室外消火栓",
            latitude: parseFloat(this.data.current_loc_latitude),
            longitude: parseFloat(this.data.current_loc_longitude),
            flowRate: this.data.flowRate,
            description: this.data.description,
            status: this.data.choose_status === "正常" ? true : false
          }
        })
      )
    })
  },

  uploadFiles(){
    this.data.imgList.forEach((item)=>{
      let filePath = item.tempFilePath
      let name = filePath.substring(filePath.lastIndexOf('/')+1)
      // 在数据库表中上传
      uploadInitFile(app,"hydrant", item, this.data.hydrantId).then((res)=>{
        if(res.key){
           // 在对象存储中上传
          handleFileUploading(name, item.tempFilePath, app)
        }else{
          wx.showModal({
            title: '出错了'
          })
        }
      })   
    })
  },

  //更新标记
  async updateItem(){
    const itemId = this.data.markerId
    var imgList = this.data.imgList
    if(this._isFormReady()){
      // 更新基本信息
      this.updateBasicInfo(itemId).then(res => {
        // 数据库中已经存储的，但在客户端被更新后删除的， 需要删除之前存在的
        res.files.forEach(item => {
          let count = 0
          imgList.forEach(image =>{
            if(!image.id || item.id !== image.id){
              count++
            }
          })
          if(count === imgList.length){
            // 删除操作 在数据库中删除 
            deleteFileFromDbs(app, "hydrant", item.id)
            // 删除操作 在cos 中删除
            deleteFile(item, app).then(res=>{
              console.log(res)
            })
          }
        })
        // 添加新图片  在数据库添加和 在对象存储中添加
        imgList.forEach(image =>{
          if(image.tempFilePath){
            let filePath = image.tempFilePath
            let name = filePath.substring(filePath.lastIndexOf('/')+1)
            uploadInitFile(app,"hydrant", image, itemId).then((res)=>{
              if(res.id){
                handleFileUploading(name, image.tempFilePath, app)
              }
            })
          }
        })
        // 更新成功
        wx.showModal({
          title: '更新成功',
          content: '更新成功',
          complete: () => {
            wx.switchTab({
              url: '../index/index',
            })
          }
        })
      })
    }else {
      wx.showModal({
        title: '填写错误，请重新填写'
      })
    }
  },

  // 更新基本信息
  updateBasicInfo(itemId){
    return new Promise((resolve) => {
      resolve(
        app.call({
          path:`/hydrant/${itemId}`,
          method: 'put',
          header: {
            'X-WX-SERVICE': 'fire-assistant-s',
            'tokens': getTokenKey()//必须添加#######
          },
          data: {
            latitude: parseFloat(this.data.current_loc_latitude),
            longitude: parseFloat(this.data.current_loc_longitude),
            flowRate: this.data.flowRate,
            description: this.data.description,
            status: this.data.choose_status === "正常" ? true : false
          }
        })
      )
    })
  },


  async deleteItem(){
    var imgList = this.data.imgList
    wx.showModal({
      title: '您确定要删除这个消火栓吗',
      complete: (res) => {
        if (res.confirm) {
          // 根据markerId删除 数据库中
          deleteMarker(app, "hydrant", this.data.markerId).then((res)=>{
            if(res){
              wx.showModal({
                title: '出错了',
                content: res.message ? res.message:res
              })
            }else{
              // 删除对象存储中的照片 可能存在问题
              imgList.forEach(item=>{
                if(item.img){
                  // 对象存储中的照片
                  deleteFile(item, app).then(res=>{
                    console.log(res)
                  })
                }
              })
              wx.showModal({
                title: '删除成功',
                complete: () => {
                  wx.switchTab({
                    url: '../index/index',
                  })
                }
              })
            } 
          })
        }
      }
    })
   
  }

})